<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Log;

class Vehicle extends BaseController
{
    /**
     * 获取车辆列表
     */
    public function getList()
    {
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 20);
        $plateNumber = input('plateNumber/s', '');
        $categoryId = input('categoryId/d', 0);
        
        // 记录请求参数
        Log::info('车辆列表请求参数: ' . json_encode([
            'page' => $page,
            'pageSize' => $pageSize,
            'plateNumber' => $plateNumber,
            'categoryId' => $categoryId
        ]));
        
        $where = [];
        if (!empty($plateNumber)) {
            $where[] = ['v.plate_number', 'like', "%{$plateNumber}%"];
        }
        if (!empty($categoryId)) {
            $where[] = ['v.category_id', '=', $categoryId];
        }
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle')) {
                Log::error('车辆表不存在');
                return json([
                    'code' => 500,
                    'msg' => '车辆表不存在',
                    'data' => [
                        'list' => [],
                        'total' => 0
                    ]
                ]);
            }
            
            $count = Db::name('vehicle')
                ->alias('v')
                ->where($where)
                ->count();
                
            $list = Db::name('vehicle')
                ->alias('v')
                ->join('vehicle_category c', 'v.category_id = c.id', 'LEFT')
                ->where($where)
                ->field('v.*, c.name as category_name')
                ->page($page, $pageSize)
                ->order('v.create_time', 'desc')
                ->select()
                ->toArray();
                
            Log::info('车辆列表查询结果: 总数=' . $count . ', 列表数=' . count($list));
            
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => [
                    'list' => $list,
                    'total' => $count
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('车辆列表查询异常: ' . $e->getMessage());
            return json([
                'code' => 500,
                'msg' => '查询异常: ' . $e->getMessage(),
                'data' => [
                    'list' => [],
                    'total' => 0
                ]
            ]);
        }
    }
    
    /**
     * 获取车辆类型
     */
    public function getCategoryList()
    {
        Log::info('获取车辆类型请求');
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle_category')) {
                Log::error('车辆类型表不存在');
                return json([
                    'code' => 500,
                    'msg' => '车辆类型表不存在',
                    'data' => []
                ]);
            }
            
            $list = Db::name('vehicle_category')
                ->field('id, name')
                ->select()
                ->toArray();
                
            // 记录查询结果
            Log::info('车辆类型查询结果: ' . json_encode($list));
                
            // 转换为树形结构
            $treeData = [];
            foreach ($list as $item) {
                $treeData[] = [
                    'id' => intval($item['id']),
                    'label' => $item['name'],
                ];
            }
            
            Log::info('车辆类型树形结构: ' . json_encode($treeData));
                
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $treeData
            ]);
        } catch (\Exception $e) {
            Log::error('车辆类型查询异常: ' . $e->getMessage());
            return json([
                'code' => 500,
                'msg' => '查询异常: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }
    
    /**
     * 添加或编辑车辆
     */
    public function doEdit()
    {
        $data = Request::post();
        Log::info('添加/编辑车辆请求数据: ' . json_encode($data));
        
        // 验证必填字段
        if (empty($data['plate_number'])) {
            return json(['code' => 400, 'msg' => '车牌号码不能为空']);
        }
        if (empty($data['fuel_type'])) {
            return json(['code' => 400, 'msg' => '燃油类型不能为空']);
        }
        if (empty($data['category_id'])) {
            return json(['code' => 400, 'msg' => '车辆类型不能为空']);
        }
        
        // 处理数据
        $saveData = [
            'plate_number' => $data['plate_number'],
            'fuel_type' => $data['fuel_type'],
            'category_id' => $data['category_id'],
            'brand_model' => $data['brand_model'] ?? '',
            'color' => $data['color'] ?? '',
            'engine_number' => $data['engine_number'] ?? '',
            'frame_number' => $data['frame_number'] ?? '',
            'purchase_date' => $data['purchase_date'] ?? null,
            'purchase_price' => $data['purchase_price'] ?? 0,
            'service_years' => $data['service_years'] ?? 0,
            'displacement' => $data['displacement'] ?? '',
            'passenger_capacity' => $data['passenger_capacity'] ?? 0,
        ];
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle')) {
                Log::error('车辆表不存在');
                return json(['code' => 500, 'msg' => '车辆表不存在']);
            }
            
            // 新增或更新
            if (isset($data['id']) && !empty($data['id'])) {
                // 更新
                $plateNumber = $data['id']; // 使用id字段存储车牌号码
                Db::name('vehicle')->where('plate_number', $plateNumber)->update($saveData);
                $msg = '更新成功';
            } else {
                // 新增
                // 检查车牌号是否已存在
                $exists = Db::name('vehicle')->where('plate_number', $data['plate_number'])->find();
                if ($exists) {
                    return json(['code' => 400, 'msg' => '该车牌号码已存在']);
                }
                
                Db::name('vehicle')->insert($saveData);
                $msg = '添加成功';
            }
            
            return json(['code' => 200, 'msg' => $msg]);
        } catch (\Exception $e) {
            Log::error('添加/编辑车辆异常: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '操作失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除车辆
     */
    public function doDelete()
    {
        $plateNumbers = Request::post('plateNumbers');
        Log::info('删除车辆请求: plateNumbers=' . $plateNumbers);
        
        if (empty($plateNumbers)) {
            return json(['code' => 400, 'msg' => '请选择要删除的车辆']);
        }
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle')) {
                Log::error('车辆表不存在');
                return json(['code' => 500, 'msg' => '车辆表不存在']);
            }
            
            $plateNumberArr = explode(',', $plateNumbers);
            Db::name('vehicle')->whereIn('plate_number', $plateNumberArr)->delete();
            
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Log::error('删除车辆异常: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 添加车辆类型
     */
    public function addCategory()
    {
        $name = Request::post('name');
        Log::info('添加车辆类型请求: name=' . $name);
        
        if (empty($name)) {
            return json(['code' => 400, 'msg' => '类型名称不能为空']);
        }
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle_category')) {
                Log::error('车辆类型表不存在');
                return json(['code' => 500, 'msg' => '车辆类型表不存在']);
            }
            
            // 检查是否已存在
            $exists = Db::name('vehicle_category')->where('name', $name)->find();
            if ($exists) {
                return json(['code' => 400, 'msg' => '该类型名称已存在']);
            }
            
            // 添加类型
            Db::name('vehicle_category')->insert(['name' => $name]);
            
            return json(['code' => 200, 'msg' => '添加类型成功']);
        } catch (\Exception $e) {
            Log::error('添加车辆类型异常: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '添加类型失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除车辆类型
     */
    public function deleteCategory()
    {
        $id = Request::post('id');
        Log::info('删除车辆类型请求: id=' . $id);
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '请选择要删除的类型']);
        }
        
        try {
            // 检查表是否存在
            if (!$this->tableExists('vehicle_category')) {
                Log::error('车辆类型表不存在');
                return json(['code' => 500, 'msg' => '车辆类型表不存在']);
            }
            
            // 检查是否有关联的车辆
            if ($this->tableExists('vehicle')) {
                $count = Db::name('vehicle')->where('category_id', $id)->count();
                if ($count > 0) {
                    return json(['code' => 400, 'msg' => '该类型下有关联车辆，不能删除']);
                }
            }
            
            // 删除类型
            Db::name('vehicle_category')->where('id', $id)->delete();
            
            return json(['code' => 200, 'msg' => '删除类型成功']);
        } catch (\Exception $e) {
            Log::error('删除车辆类型异常: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '删除类型失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 检查表是否存在
     */
    private function tableExists($tableName)
    {
        try {
            $prefix = config('database.connections.mysql.prefix');
            $fullTableName = $prefix . $tableName;
            
            $result = Db::query("SHOW TABLES LIKE '{$fullTableName}'");
            return !empty($result);
        } catch (\Exception $e) {
            Log::error('检查表是否存在异常: ' . $e->getMessage());
            return false;
        }
    }
}